package com.shu.driftbook.ajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class getBookInfo extends HttpServlet{
	protected void processRequest(HttpServletRequest request,HttpServletResponse response,String method)
			throws IOException, ClassNotFoundException, SQLException{
		 response.setContentType("text/html;charset=UTF-8");
		 PrintWriter out = response.getWriter();  
	        try {  
	            response.setContentType("text/html");  
	            response.setHeader("Cache-Control", "no-store");  
	            response.setHeader("Pragma", "no-cache");  
	            response.setDateHeader("Expires", 0);
	            Class.forName("com.mysql.jdbc.Driver");
	            Connection con=DriverManager.getConnection("jdbc:mysql://211.101.12.143/drift?useUnicode=true&amp;characterEncoding=UTF-8","root","shuos");
	            Statement stm=con.createStatement();
	            String bookid = request.getParameter("bookid");
	            String bookname = null, author = null, ISBN = null, publisher = null;
	            if(bookid!=null) {  
	            	ResultSet rs=stm.executeQuery("select bookname, author, ISBN, publisher from book where bookid=" + bookid + ";");
	            	if(rs.next()){
	            		bookname = rs.getString("bookname");
	            		author = rs.getString("author");
	            		ISBN = rs.getString("ISBN");
	            		publisher = rs.getString("publisher");
	            	}
	            	String str = "<h2>" + bookname + "</h2>\n<ul>\n  <li>作者: "
	            			+ author + "</li>\n  <li>ISBN: "
	            			+ ISBN + "</li>\n  <li>出版社: " 
	            			+ publisher + "</li>\n</ul>";
	            	//System.out.println(str);
	            	out.write(str);
	            }  
	        }
	        finally{
	        	out.close();
	        }
        }
	 protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
	  {
	    try {
			processRequest(request,response,"GET");
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  }

	  protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
	  {
	    try {
			processRequest(request,response,"POST");
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  }
}
